'use strict';

webappApp.service('photoService', ['$resource', 'webRoot', 'queue', function($resource, webRoot, queue) {
  var serve = $resource(webRoot + '/photo/:id'),
      upload = $resource(webRoot + '/photo/upload');

  this.uploads = {};

  this.isComplete = function () {
    return !(queue.status.queued || queue.status.executing);
  };

  this.get = function (id, onsuccess, onerror) {
    return serve.get({
      id: id
    }, onsuccess, onerror);
  };

  this.upload = function (photo) {
    this.uploads[photo.name] = photo;
    queue.push(function () {
      var formData = new FormData(),
        xhr = new XMLHttpRequest(),
        task = this;

      formData.append(photo.name, photo.file);
      formData.append('id', photo.id);
      formData.append('orientation', photo.orientation);
      upload.get(function (link) {
        xhr.open('POST', link.link, true);
        xhr.onprogress = function (e) {
          photo.onprogress(photo, e);
        };

        xhr.onerror = function (e) {
          photo.onerror(photo, e);
          queue.pop(task);
        };

        xhr.onload = function (e) {
          photo.onload(photo, e);
          queue.pop(task);
        };

        // multipart/form-data
        xhr.send(formData);
      });
    });
  };
}]);
